package LinkedList;

public class _24_SwapNodesinPairs {

    public ListNode swapPairs(ListNode head) {
        if(head==null || head.next==null) return head;
        ListNode odd = head,even = head.next;
        ListNode begin = even;
        while(even.next!=null && even.next.next!=null){
            ListNode temp = even.next;
            even.next = odd;
            odd.next = temp.next;
            odd = temp;
            even = temp.next;
        }
        if(even.next!=null){
            ListNode temp = even.next;
            even.next = odd;
            odd.next = temp;
        }else{
            even.next = odd;
            odd.next = null;
        }
        return begin;
    }

    //递归的方法解决
    public ListNode swapPairs1(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode nextNode  = head.next;
        head.next = swapPairs1(nextNode.next);
        nextNode.next = head;
        return nextNode;
    }
}
